<template>
  <div>
    <el-card shadow="never" class="mt-16px">
      <template #header>
        <span>{{ infoOptions.data?.name || '--' }}</span>
      </template>
      <el-descriptions :column="infoOptions.column">
        <div v-for="(item, index) in infoOptions.columns" :key="index">
          <el-descriptions-item :label="item.label">{{
            infoOptions.data[item.key] || '--'
          }}</el-descriptions-item>
        </div>
      </el-descriptions>
      <el-descriptions :column="filedOptions.column" class="mt-16px">
        <div v-for="(item, index) in filedOptions.columns" :key="index">
          <el-descriptions-item
            label-class-name="font-size-16px"
            class-name="font-size-16px"
            :label="item.label"
            >{{ filedOptions.data[item.key] || '0' }}</el-descriptions-item
          >
        </div>
      </el-descriptions>
    </el-card>
    <el-card shadow="never" class="mt-16px">
      <el-form label-width="100px" ref="formRef" :model="searchValue">
        <el-row>
          <el-col :span="6">
            <el-form-item label="表名称" prop="table">
              <ns-input v-model="searchValue.table" clearable placeholder="请输入表名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="表描述" prop="remark">
              <ns-input v-model="searchValue.remark" clearable placeholder="请输入表描述" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="所属库" prop="database">
              <ns-input v-model="searchValue.database" clearable placeholder="请输入所属库" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="分类" prop="classification">
              <el-cascader
                v-model="searchValue.classification"
                placeholder="请选择分类"
                :props="classificationCascaderProps"
                :options="classificationList"
                filterable
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="分级" prop="level">
              <el-select v-model="searchValue.level" clearable placeholder="请选择分级">
                <el-option
                  v-for="(level, levelIndex) in levelList"
                  :key="levelIndex"
                  :label="level.levelName"
                  :value="level.levelCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否已分级">
              <el-select v-model="searchValue.isLevel" clearable placeholder="请选择是否已分级">
                <el-option label="已分级" :value="true" />
                <el-option label="未分级" :value="false" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" class="text-right">
            <el-button @click="searchReset" plain>重置</el-button>
            <el-button @click="search" plain>搜索</el-button>
          </el-col>
        </el-row>
      </el-form>
      <el-divider />
      <el-button type="primary" :disabled="ids.length == 0" @click="recheckList('1')"
        >复核通过</el-button
      >
      <el-button plain :disabled="ids.length == 0" @click="recheckList('0')">复核不通过</el-button>
      <AsyncTable
        class="mt-12px"
        ref="tableRef"
        :fetchData="fetchData"
        @selection-change="changeTable"
        v-bind="tableOptions"
      />
    </el-card>
  </div>
</template>

<script setup lang="tsx">
import { getDataSourceDetail, assetPageByLevelCount, assetMessageRechecks } from '@/api/assetList'
import { getAssetByLevel } from '@/api/assetDetail'
import { levelPage } from '@/api/strategyManage/level/index'
import { dataClassificationTree } from '@/api/dataStandards/classification/index'
import dayjs from 'dayjs'
import { renderClassification, renderLevel, recheckStatusRender } from '@/utils/commonRender'
import { recheckStatusMap } from '@/utils/dict'
const { proxy } = getCurrentInstance() as any
const route = useRoute()
const assetId = ref<string>(route.query.id as string)

const formRef = ref()
const tableRef = ref()

const classificationCascaderProps = ref({
  checkStrictly: true,
  label: 'text',
  value: 'id',
  children: 'children',
  emitPath: false
})
const infoOptions = reactive({
  column: 5,
  columns: [
    { label: '归属机构：', key: 'deptName', isShow: false },
    { label: '归属系统：', key: 'sysName', isShow: true },
    { label: '数据标准：', key: 'templateName', isShow: true },
    // { label: '分类分级方式：', key: 'classificationWay', isShow: true },
    { label: '启动时间：', key: 'startTime', isShow: true },
    { label: '完成时间：', key: 'completeTime', isShow: true }
  ],
  data: {}
})
const filedOptions = reactive({
  column: 5,
  columns: [
    { label: '总数：', key: 'totalCount' },
    { label: '已分级数：', key: 'level' },
    { label: '未分级数：', key: 'unLevel' }
  ],
  data: {}
})
const ids = ref<string[]>([])

const searchValue = ref({
  column: '',
  comment: '',
  database: '',
  table: '',
  importance: '',
  classification: '',
  level: '',
  remark: '',
  isLevel: ''
})

// 搜索重置
const searchReset = () => {
  formRef.value.resetFields()
  tableRef.value.resetPage()
  tableRef.value.fetchData()
}
// 搜索
const search = () => {
  tableRef.value.resetPage()
  tableRef.value.fetchData()
}

const allSelect = ref(false)
const allSelectHandle = () => {
  allSelect.value = !allSelect.value
  tableRef.value.ignorePageSelect(allSelect.value)
}

// 表格数据获取
const fetchData = async ({ page, pageSize }) => {
  const params = {
    page,
    pageSize,
    ...searchValue.value,
    dataSourceId: assetId.value,
    dataType: 'table'
  }
  const { data, count } = await getAssetByLevel(params)
  return { data, count }
}
const changeTable = (val) => {
  ids.value = []
  val.map((item) => {
    ids.value.push(item.id)
  })
}

const recheckList = async (status) => {
  proxy?.$modal
    .confirm(`确定要将所选资产复核${recheckStatusMap.get(status)}吗？`)
    .then(async () => {
      const data = await assetMessageRechecks({
        ids: ids.value,
        recheckStatus: status
      })
      console.log('data', data)
      if (data) {
        tableRef.value.fetchData()
        ElMessage.success('提交成功')
      }
    })
    .catch(() => {})
}

const tableOptions = reactive({
  columns: [
    {
      type: 'selection'
    },
    { label: '表名称', prop: 'table' },
    { label: '表描述', prop: 'remark' },
    { label: '所属库', prop: 'database' },
    {
      label: '分类',
      render({ row }) {
        return (
          <>
            <span>
              {row.recheckClassificationName
                ? row.recheckClassificationName
                : row.handClassificationName
                  ? `${row.handClassificationName}`
                  : row.classificationName
                    ? `${row.classificationName}`
                    : '--'}
            </span>
          </>
        )
      }
    },
    {
      label: '分级',
      render({ row }) {
        let level
        if (row.recheckLevelName) {
          level = `${row.recheckLevelName}`
        } else if (row.handLevelName) {
          level = `${row.handLevelName}`
        } else if (row.levelName) {
          level = `${row.levelName}`
        } else {
          level = '--'
        }
        return (
          <>
            <span>{level}</span>
          </>
        )
      }
    },
    {
      label: '状态',
      render: recheckStatusRender
    },
    {
      label: '操作',
      render: ({ row }) => {
        return (
          <>
            <el-button link type="primary" onClick={() => recheck(row)}>
              复核
            </el-button>
          </>
        )
      }
    }
  ],
  data: []
})

// 分级分类（行）
const recheck = (row) => {
  proxy?.$Drawer({
    params: {
      ...row,
      type: row.handClassificationName ? `人工` : row.classificationName ? `自动` : '--',
      callBack: () => {
        tableRef.value.resetPage()
        tableRef.value.fetchData()
      }
    },
    title: `复核`,
    size: '40%',
    component: import('./recheck.vue')
  })
}

const getDetail = async () => {
  const res = await getDataSourceDetail({ id: assetId.value })
  infoOptions.data = res.data
  console.log('infoOptions.data', infoOptions.data)
  const data = await assetPageByLevelCount({ dataSourceId: assetId.value, dataType: 'table' })
  filedOptions.data = data
}

const levelList = ref([])
const getLevelList = async () => {
  const { data } = await levelPage({ page: 1, pageSize: 999 })
  console.log('data', data)
  levelList.value = data
}

const classificationList = ref([])
const getClassificationList = async () => {
  const data = await dataClassificationTree({ type: 1 })
  classificationList.value = traverseTree(data)
}
function traverseTree(data) {
  const updatedTree = []
  for (let i = 0; i < data.length; i++) {
    const node = data[i] // 创建新节点并添加 disable 属性
    if (node.pid == '-1') {
      node.disabled = true
    }
    updatedTree.push(node)
    if (node.children && node.children.length > 0) {
      node.children = traverseTree(node.children) // 递归遍历子节点并更新子树结构
    }
  }
  return updatedTree
}
onMounted(() => {
  getLevelList()
  getClassificationList()
  getDetail()
})
</script>
